﻿using System.Collections.Generic;
using System;

namespace AutoChess
{
    public class ActionQueueList 
    {
        //行动队列
        private List<ActionObject> actionQueueList;
        //强制停止回调
        private Action onForceStop;

        private ActionObject _currendAction;
        private bool _Run = false;
        public bool Runing
        {
            get { return _Run; }
        }
        public ActionQueueList()
        {
            actionQueueList = new List<ActionObject>();
            _currendAction = null;
        }

        public void Relase()
        {
            actionQueueList = new List<ActionObject>();
            _currendAction = null;
        }

        /// <summary>
        /// 添加一个行动
        /// </summary>
        /// <param name="action"></param>
        /// <param name="delayTime"></param>
        public void EnqueueAction(Action action , float delayTime , int priority)
        {
            var actData = new ActionObject();
            actData.InitAction(action, delayTime, priority);
            EnqueueAction(actData);
        }
        public void EnqueueAction(ActionObject newAction)
        {
            actionQueueList.Add(newAction);
        }
        /// <summary>
        /// 调用开始
        /// </summary>
        /// <param name="forceStop"></param>
        public void ActionQueueStart(Action forceStop)
        {
            if (actionQueueList.Count > 0)
            {
                actionQueueList.Sort((a, b) => { return a.Priority.CompareTo(b.Priority); });
                this.onForceStop = forceStop;
                this._Run = true;
            }
            else
            {
                this._Run = false;
            }
        }
        /// <summary>
        /// 强制结束
        /// </summary>
        public void ActionQueueStop()
        {
            actionQueueList.Clear();
            this._Run = false;
            if (onForceStop != null)
            {
                onForceStop();
                onForceStop = null;
            }
        }

        public void Tick(float deltaTime)
        {
            if (!_Run)
                return;
            if (_currendAction == null)
            {
                if (actionQueueList.Count > 0)
                {
                    _currendAction = actionQueueList[0];
                    actionQueueList.RemoveAt(0);
                }
                else
                {
                    this._Run = false;
                    onForceStop = null;
                }
            }
            else
            {
                _currendAction.Tick(deltaTime);
                if (_currendAction.IsFinished)
                {
                    _currendAction = null;
                }
            }
        }
    }
}
